package com.kun.controller;

import com.kun.mapper.AdminMapper;
import com.kun.mapper.HandleOrderMapper;
import com.kun.mapper.OrderMapper;
import com.kun.mapper.UserMapper;
import com.kun.pojo.Admin;
import com.kun.pojo.HandleOrder;
import com.kun.pojo.Order;
import com.kun.pojo.User;
import com.kun.service.AdminService;
import com.kun.service.HandleOrderService;
import com.kun.service.OrderService;
import com.kun.service.UserService;
import com.kun.utils.EmailUtil.SendEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;

/**
 * @Version:v1.0
 * @Author: 鲁坤
 * @Date: 2021-03-15
 * @ClassName: AdminController
 * @Description: 管理员控制类
 */
@Controller
public class AdminController {
//    @Autowired
//    private AdminMapper adminMapper;
    @Autowired
    private AdminService adminService;
//    @Autowired
//    private UserMapper userMapper;
    @Autowired
    private UserService userService;
//    @Autowired
//    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
//    @Autowired
//    private HandleOrderMapper handleOrderMapper;
    @Autowired
    private HandleOrderService handleOrderService;
    @Autowired
    JavaMailSenderImpl mailSender;
    /*-----------------------------管理员登录-----------------------------*/
    //跳转到管理员首页
    @RequestMapping("/admin_index")
    public String adminIndex(){
        return "admin_index";
    }
    //跳转到管理员登录界面
    @RequestMapping("/admin")
    public String ToAdminLogin(){
        return "admin_login";
    }
    //输入信息检查
    @RequestMapping("/admincheck")
    public String AdminCheck(Model model,
                             @RequestParam(value = "username")String username,
                             @RequestParam(value = "password")String password,
                             HttpServletResponse response,
                             HttpSession session) throws IOException {
        //Admin admin = adminMapper.queryAdminByUsername(username);
        Admin admin = adminService.queryAdminByUsername(username);
        if(admin==null){//判断账号存在性
            model.addAttribute("msg","该账户不存在");
            return "admin_login";
        }else{
            if(!(admin.getPassword()).equals(password)){
                model.addAttribute("username",username);
                model.addAttribute("msg","密码错误，请重试");
                return "admin_login";
            }else{
                PrintWriter writer = response.getWriter();
                response.setContentType("text/html;charset=UTF-8");
                writer.print("<script>alert('登录成功');</script>");
                writer.flush();
                session.setAttribute("trueadmin",admin);
                session.setAttribute("identity",username);
                return "admin_index";
            }
        }

    }
    /*-----------------------------用户注册审批-----------------------------*/
    @RequestMapping("/user_register")
    public String HandleRegister(Model model){
        //获取所有申请 0代表未审核通过
        //List<User> users = userMapper.queryUserByRstatus(0);      //不用缓存
        List<User> users = userService.queryUserByRstatus(0);       //使用缓存
        model.addAttribute("allusers",users);
        return "admin_stream";
    }
    //同意申请
    @RequestMapping("/admit_user/{uid}")
    public String AdmitUser(Model model,
                            @PathVariable("uid") int uid,
                            @RequestParam(value = "changerstatus",required = false)int status){
        //User user = userMapper.queryUserByUid(uid);               //不用缓存
        User user = userService.queryUserByUid(uid);                //使用缓存

        user.setRstatus((user.getRstatus()+status)%2);              //重置用户注册状态
        user.setLstatus(1);                                         //在第一次审核通过时，同时授予登录权限
        //userMapper.updateUser(user);                              //不用缓存
        userService.updateUser(user);                               //使用缓存

        //List<User> users = userMapper.queryUserByRstatus(0);      //不用缓存
        List<User> users = userService.queryUserByRstatus(0);       //使用缓存
        model.addAttribute("allusers",users);

        //发送邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(user.getUsername()+"你好呀");

        mailMessage.setText("恭喜"+user.getUsername()+"成为LTable的新用户");

        mailMessage.setTo(user.getEmail());
        mailMessage.setFrom("13100626808@163.com");
        mailSender.send(mailMessage);

        return "admin_stream";
    }
    //拒绝申请并清除数据
    @RequestMapping("/refuse_user/{uid}")
    public String RefuseUser(Model model,
                            @PathVariable("uid") int uid){
        //User user = userMapper.queryUserByUid(uid);               //不用缓存
        User user = userService.queryUserByUid(uid);                //使用缓存
        //发送邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(user.getUsername()+"你好");

        mailMessage.setText("由于您资质不符，已拒绝您的申请");

        mailMessage.setTo(user.getEmail());
        mailMessage.setFrom("13100626808@163.com");
        mailSender.send(mailMessage);
        //userMapper.deleteUserByUid(uid);                          //不用缓存
        userService.deleteUserByUid(uid);                           //使用缓存
        return "admin_stream";
    }
    /*-----------------------------用户登录权限修改-----------------------------*/
    @RequestMapping("/admin_user")
    public String Admin_user(Model model){                          //查询所有已经注册通过的用户
        //List<User> users = userMapper.queryUserByRstatus(1);      //不用缓存
        List<User> users = userService.queryUserByRstatus(1);       //使用缓存
        model.addAttribute("allusers",users);
        return "admin_user";
    }
    //这个地方 使用Redis做缓存出现问题
    @RequestMapping("/admit_user_login/{uid}")
    public String AdmitUserLogin(Model model,
                                 @PathVariable("uid")int uid,
                                 @RequestParam("changelstatus")int changelstatus){
        //User user = userMapper.queryUserByUid(uid);               //不用缓存
        User user = userService.queryUserByUid(uid);                //使用缓存
        user.setLstatus((user.getLstatus()+changelstatus)%2);

        //userMapper.updateUser(user);                              //不用缓存
        userService.updateUser(user);                               //使用缓存

        //List<User> users = userMapper.queryUserByRstatus(1);      //不用缓存
        List<User> users = userService.queryUserByRstatus(1);       //使用缓存
        model.addAttribute("allusers",users);
        return "admin_user";
    }
    /*-----------------------------工单处理-----------------------------*/
    //跳转至待处理工单页面 按照紧急程度降序排列
    @RequestMapping("/admin_handle_order")
    public String AdminHandleOrder(Model model){
        //List<Order> orders = orderMapper.getOrderByStatus(1);         //不用缓存
        List<Order> orders = orderService.getOrderByStatus(1);  //使用缓存
        model.addAttribute("orders",orders);
        return "admin_handle_order";
    }
    //进入具体某一工单处理页面 历史信息将在此展示
    @RequestMapping("/admin_handle_order/{oid}")
    public String AdminHandleOrderDetail(@PathVariable("oid")int oid,
                                         HttpSession session,
                                         Model model,
                                         @RequestParam(value = "admin_reply_copy",required = false)String admin_reply_copy){
        //处理当前工单时，需要把工单的id存入session
        session.setAttribute("adminnowoid",oid);
        //System.out.println(oid);
        //Order order = orderMapper.getOrderByOid(oid);                 //不用缓存
        Order order = orderService.getOrderByOid(oid);                  //使用缓存
        //如何将数据展示出来？？？
        //List<HandleOrder> handleOrders = handleOrderMapper.queryAnswerByOid(oid);     //不用缓存
        List<HandleOrder> handleOrders = handleOrderService.queryAnswerByOid(oid);      //使用缓存
        model.addAttribute("adminhandleorder",handleOrders);
        model.addAttribute("adminorder",order);

        //System.out.println(admin_reply_copy);
        if(admin_reply_copy!=null&& !admin_reply_copy.equals("")){
            session.setAttribute("admin_reply",admin_reply_copy);
        }

        return "admin_handle_order_detail";
    }
    //管理员信息回复
    @RequestMapping("/admin_answer")
    public String AdminAnswer(Model model,
                              HttpSession session,
                              @RequestParam("admin_reply")String admin_reply){
        int oid = (int)session.getAttribute("adminnowoid");
        //回复不为空 才能回复成功
        if(admin_reply!=null&&!admin_reply.equals("")){
            Admin trueadmin = (Admin) session.getAttribute("trueadmin");
            String username = trueadmin.getUsername();
            //String username = (String) session.getAttribute("identity");

            Timestamp replytime = new Timestamp(System.currentTimeMillis());
            HandleOrder handleOrder = new HandleOrder(oid, username, 1, admin_reply, replytime);
            //handleOrderMapper.addAnswer(handleOrder);             //不用缓存
            handleOrderService.addAnswer(handleOrder);              //使用缓存
            session.removeAttribute("admin_reply");
        }
        //Order order = orderMapper.getOrderByOid(oid);             //不用缓存
        Order order = orderService.getOrderByOid(oid);              //使用缓存
        //List<HandleOrder> handleOrders = handleOrderMapper.queryAnswerByOid(oid);     //不用缓存
        List<HandleOrder> handleOrders = handleOrderService.queryAnswerByOid(oid);      //使用缓存
        model.addAttribute("adminhandleorder",handleOrders);
        model.addAttribute("adminorder",order);
        return "admin_handle_order_detail";
    }

    //管理员查看历史工单
    @RequestMapping("/admin_history_order")
    public String AdminHistoryOrder(Model model){
        //List<Order> orders = orderMapper.getOrderByStatus(0);             //不用缓存
        List<Order> orders = orderService.getOrderByStatus(0);      //使用缓存
        model.addAttribute("orders",orders);
        return "admin_history_order";
    }
    //管理员查看工单详情
    @RequestMapping("/admin_order_detail/{oid}")
    public String AdminOrderDetail(@PathVariable("oid")int oid,
                                   Model model){
        //Order order = orderMapper.getOrderByOid(oid);                     //不用缓存
        Order order = orderService.getOrderByOid(oid);                      //使用缓存
        //如何将数据展示出来？？？
        //List<HandleOrder> handleOrders = handleOrderMapper.queryAnswerByOid(oid);     //不用缓存
        List<HandleOrder> handleOrders = handleOrderService.queryAnswerByOid(oid);      //使用缓存
        model.addAttribute("adminhandleorder",handleOrders);
        model.addAttribute("adminorder",order);
        return "admin_order_detail";
    }
}
